package com.dr.service.impl;

import com.dr.Enum.ExcepEnum;
import com.dr.common.pojo.FileFinalValue;
import com.dr.common.ution.DateUtil;
import com.dr.common.ution.StringUtil;
import com.dr.db.LocationMapper;
import com.dr.exception.ServiceExcep;
import com.dr.pojo.Location;
import com.dr.service.LocationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by tugou on 2017/5/3.
 * 驾校地址服务实现类
 */
@Service
public class LocationServiceImpl implements LocationService{

    @Autowired
    LocationMapper locationMapper;

    @Override
    public List<Location> getAllLocation(Location location) {
        List<Location> list = locationMapper.getLocation(location);
        return list;
    }

    @Override
    public Location getLocationById(String id) {
        Location location = new Location();
        location.setId(Long.valueOf(id));
        List<Location> list = locationMapper.getLocation(location);
        if(list != null && list.size()>0)
            return list.get(0);
        return null;
    }

    @Override
    public void saveLocation(Location location) throws ServiceExcep {
        location.setState(1);
        location.setCreateDate(DateUtil.now());
        int resultCount = locationMapper.insertLocation(location);
        if(resultCount == 0){
            throw new ServiceExcep(ExcepEnum.INSERTDATAEMPTY.getName(),ExcepEnum.INSERTDATAEMPTY.getIndex());
        }
    }

    @Override
    public void updateLocation(Location location) throws ServiceExcep {
        location.setState(1);
        location.setCreateDate(DateUtil.now());
        int resultCount = locationMapper.updateLocation(location);
        if(resultCount == 0){
            throw new ServiceExcep(ExcepEnum.INSERTDATAEMPTY.getName(),ExcepEnum.INSERTDATAEMPTY.getIndex());
        }
    }

    @Override
    public void deleteLocation(String id) throws ServiceExcep {
        Location loc = new Location();
        loc.setId(Long.valueOf(id));
        loc = locationMapper.getLocation(loc).get(0);
        if (loc.getState() == 0){
            loc.setState(1);
        }else{
            loc.setState(0);
        }
        int resultCount = locationMapper.updateLocation(loc);
        if(resultCount == 0){
            throw new ServiceExcep(ExcepEnum.DELETEERROR.getName(),ExcepEnum.DELETEERROR.getIndex());
        }
    }

    @Override
    public void commitLocation(Location location) throws ServiceExcep {
        if(location == null)
            throw  new ServiceExcep(ExcepEnum.PARERROR.getName(),ExcepEnum.PARERROR.getIndex());
        if(StringUtil.isEmpty(location.getBgPicture())){
            location.setBgPicture(FileFinalValue.BGPICTURE+FileFinalValue.DEFULTPICTURE);
        }
        if(location.getId() != null){
            this.updateLocation(location);
        }
        else{
            this.saveLocation(location);
        }
    }
}
